/*
 * @Author: 郑子胜(Zechariahzheng)
 * @Date: 2023-11-13 09:35:23
 * @LastEditors: 郑子胜(Zechariahzheng)
 * @LastEditTime: 2023-11-21 15:29:02
 * @Descripttion: 
 */
#include "MyServo.h"

void MyServo::init(const MyServoInfo *info) {
  this->servo = new Servo();
  this->servo->attach(info->pin, 500, 2500);

  this->info = info;
  // 设置到0
  this->servo->write(0);
}

void MyServo::loop(String nowTime) {
  int day = nowTime.charAt(0)-'0';

  // 开机标志
  if (this->info->onSwitch[0] == '1') {
    int aOnWeek[7] = {0};
    String sOnWeek = String(this->info->onWeek);
    char *tmpOnWeek = new char[sOnWeek.length()+1];
    memset(tmpOnWeek, 0, sOnWeek.length()+1);
    memcpy(tmpOnWeek, this->info->onWeek, sOnWeek.length());
    char *token = strtok(tmpOnWeek, ",");
    while (token!=NULL) {
      aOnWeek[atoi(token)] = 1;
      token = strtok(NULL, ",");
    }
    free(tmpOnWeek);
    // 是当天
    if (aOnWeek[day]) {
      // 到时间点
      if (strcmp(nowTime.substring(2).c_str(), this->info->onExecuteTime) == 0) {
        // 执行动作 返回动作
        SERVO_DEBUG_PRINTLN("It's time to turn on");
        this->servo->write(atoi(this->info->onPushDepth));
        delay(1000*atoi(this->info->onLastTime));
        this->servo->write(0);
      }
    }
  }
  // 关机标志
  if (this->info->offSwitch[0] == '1') {
    int aOffWeek[7] = {0};
    String sOffWeek = String(this->info->offWeek);
    char *tmpOffWeek = new char[sOffWeek.length()+1];
    memset(tmpOffWeek, 0, sOffWeek.length()+1);
    memcpy(tmpOffWeek, this->info->offWeek, sOffWeek.length());
    char *token = strtok(tmpOffWeek, ",");
    while (token!=NULL) {
      aOffWeek[atoi(token)] = 1;
      token = strtok(NULL, ",");
    }
    free(tmpOffWeek);
    // 是当天
    if (aOffWeek[day]) {
      // 到时间点
      if (strcmp(nowTime.substring(2).c_str(), this->info->offExecuteTime) == 0) {
        // 执行动作 返回动作
        SERVO_DEBUG_PRINTLN("It's time to turn off");
        this->servo->write(atoi(this->info->onPushDepth));
        delay(1000*atoi(this->info->onLastTime));
        this->servo->write(0);
      }
    }
  }
}

void MyServo::toDoNow(const char *puhDepth, const char *lastTime) const {
  SERVO_DEBUG_PRINTLN("servo to do now!");
  SERVO_DEBUG_PRINTLN(puhDepth);
  SERVO_DEBUG_PRINTLN(lastTime);
  this->servo->write(atoi(puhDepth));
  delay(1000*atoi(lastTime));
  this->servo->write(0);
}

MyServo::~MyServo() {
  free(this->servo);
}